/*
 * @lc app=leetcode.cn id=16 lang=typescript
 *
 * [16] 最接近的三数之和
 */

// @lc code=start
function threeSumClosest(nums: number[], target: number): number {

  nums.sort((a, b) => a - b)
  let q = []
  for (let i = 0; i < nums.length; i++) {

    let left = i + 1;
    let right = nums.length - 1;
    while (left < right) {
      const sum = nums[left] + nums[right] + nums[i];

      if (sum === target) {
        return target
      }
      // a = Math.min(Math.abs(target - a), Math.abs(sum - a));
      if (sum > target) {
        q[sum - target] = sum
        right--
      } else {
        q[target - sum] = sum
        left++
      }

    }
  }

  return q.find(n => n != undefined)
};
// @lc code=end